package com.wst.wst_server.fiflter;

import com.wst.wst_server.entity.LoginUser;
import com.wst.wst_server.entity.User;
import com.wst.wst_server.mapper.UserMapper;
import com.wst.wst_server.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    UserMapper userMapper;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 1 从请求头中获取token，
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            System.out.println("jwt过滤器解析token，不合法");
            filterChain.doFilter(request, response);
            return;
        }
        //
        String userid;
        try {
            //2.JWT解析token，获得userid，验证token合法性
            Claims claims = JwtUtil.parseJWT(token);
            userid = claims.getSubject();
            System.out.println("jwt过滤器解析token，得到userid：" + userid);

        } catch (Exception e) {
            throw new RuntimeException("token非法");
        }
        //3. 从数据库中获取用户信息
        User user = userMapper.selectById(userid);

        // 4.从数据库中获取用户权限
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        List<String> menus = userMapper.getMenusByUserid(user.getId());
        for(String menu : menus){
            authorities.add(new SimpleGrantedAuthority(menu));
        }
        //5 将用户信息和用户权限存入SecurityContextHolder中
        LoginUser loginUser = new LoginUser(user);
        loginUser.setAuthorities(authorities);
        Authentication authentication = new UsernamePasswordAuthenticationToken(loginUser, null, null);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        filterChain.doFilter(request, response);
    }
}
